package com.isunland.managesystem.utils;

import android.content.Context;
import android.text.TextUtils;
import com.isunland.managesystem.R;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 日期工具类
 *
 * @author wangyanan
 */
@SuppressWarnings("all") public class MyDateUtil {
  public static final String TYPE_ALL = "yyyy-MM-dd HH:mm:ss";
  public static final String TYPE_MINITE = "yyyy-MM-dd HH:mm";
  public static final String TYPE_HOUR = "yyyy-MM-dd HH";
  public static final String TYPE_DATE = "yyyy-MM-dd";
  public static final String TYPE_MONTH = "yyyy-MM";
  public static final String TYPE_YEAR = "yyyy";
  public static final String TYPE_DATE4 = "yyyyMM";
  public static final String TYPE_DATE5 = "yyyy年MM月dd日";
  public static final String TYPE_DATE6 = "yyyyMMddHHmm";
  private static DateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
  private static DateFormat sFormatSimple;

  /**
   * 获取间隔多少天
   *
   * @throws ParseException
   */
  public static String getBetweenDays(String t1, String t2) throws ParseException {

    long l = getBetweenMills(t1, t2);
    long day = l / (24 * 60 * 60 * 1000);

    return day + "";
  }

  /**
   * 获取间隔多少毫秒
   *
   * @param t2 结束时间字符串
   * @throws ParseException
   */
  public static long getBetweenMills(String t1, String t2) throws ParseException {
    java.util.Date now = sFormat.parse(t2);
    java.util.Date date = sFormat.parse(t1);
    long l = now.getTime() - date.getTime();
    return l;
  }

  /**
   * 获取间隔多少小时(最大值24小时)
   *
   * @throws ParseException
   */
  public static String getBetweenHours(String t1, String t2) throws ParseException {

    long l = getBetweenMills(t1, t2);
    long day = l / (24 * 60 * 60 * 1000);
    long hour = (l / (60 * 60 * 1000) - day * 24);
    // long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
    // long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
    // System.out.println("" + day + "天" + hour + "小时" + min + "分" + s +
    // "秒");
    return hour + "";
  }

  /**
   * 获取间隔多少小时(最大值24小时)
   *
   * @throws ParseException
   */
  public static String getBetweenMinites(String t1, String t2) throws ParseException {

    long l = getBetweenMills(t1, t2);
    long day = l / (24 * 60 * 60 * 1000);
    long hour = (l / (60 * 60 * 1000) - day * 24);
    long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
    // long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
    // System.out.println("" + day + "天" + hour + "小时" + min + "分" + s +
    // "秒");
    return min + "";
  }

  /**
   * 获取间隔小时
   *
   * @throws ParseException
   */
  public static String getBetweenHoursAll(String t1, String t2) throws ParseException {

    long l = getBetweenMills(t1, t2);
    // long day = l / (24 * 60 * 60 * 1000);
    long hour = (l / (60 * 60 * 1000));
    // long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
    // long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
    // System.out.println("" + day + "天" + hour + "小时" + min + "分" + s +
    // "秒");
    return hour + "";
  }

  @Deprecated public static String dateToString(Date date) {
    return sFormat.format(date).toString();
  }

  /**
   * 已弃用,使用parseStringToDate或parseStringToTime代替.
   */
  @Deprecated public static Date stringToDate(String dateString) {
    try {
      return sFormat.parse(dateString);
    } catch (Exception e) {
      // Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }

  public static Date stringToDate(String dateString, String formatstr) {
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat(formatstr, Locale.CHINA);
      return dateFormat.parse(dateString);
    } catch (Exception e) {
      // Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }

  public static boolean before(String dateStartStr, String dateEndStr) {
    Date startDate;
    Date endDate;
    try {
      startDate = sFormat.parse(dateStartStr);
      endDate = sFormat.parse(dateEndStr);
      if (startDate.before(endDate)) {
        return true;
      } else {
        return false;
      }
    } catch (ParseException e) {
      // Auto-generated catch block
      e.printStackTrace();
      return false;
    }
  }

  @Deprecated public static String dateToString(Date date, String type) {
    if (type == null || date == null) {
      return null;
    }
    sFormatSimple = new SimpleDateFormat(type, Locale.CHINA);
    return sFormatSimple.format(date).toString();
  }

  /**
   * 解析日期,yyyy-MM-dd
   */
  @Deprecated public static String parseDateToString(Date date) {
    return parseTimeToString(date, MyDateUtil.TYPE_DATE);
  }

  /**
   * 解析日期,yyyy-MM-dd
   */
  @Deprecated public static Date parseStringToDate(String date) {
    return parseStringToTime(date, MyDateUtil.TYPE_DATE);
  }

  @Deprecated public static Date parseStringToTime(String date) {
    return parseStringToTime(date, MyDateUtil.TYPE_ALL);
  }

  /**
   * 解析时间yyyy-MM-dd HH:mm:ss
   */
  @Deprecated public static String parseTimeToString(Date date) {
    return parseTimeToString(date, MyDateUtil.TYPE_ALL);
  }

  public static String format(Date date) {
    return format(date, null);
  }

  public static String format(Date date, String format) {
    if (TextUtils.isEmpty(format)) format = TYPE_ALL;
    if (date == null) return null;
    String result = null;
    try {
      result = android.text.format.DateFormat.format(format, date).toString();
    } catch (Exception e) {

    }
    return result;
  }

  public static Date parse(String str) {
    return parse(str, null);
  }

  public static Date parse(String str, String format) {
    if (MyStringUtil.isEmpty(format)) format = TYPE_ALL;
    if (MyStringUtil.isEmpty(str)) return null;
    str.trim();
    Date date = null;
    try {
      date = new SimpleDateFormat(format, Locale.CHINA).parse(str);
    } catch (Exception e) {
      try {
        date = new SimpleDateFormat(TYPE_ALL, Locale.CHINA).parse(str);
      } catch (Exception e1) {
        try {
          date = new SimpleDateFormat(TYPE_MINITE, Locale.CHINA).parse(str);
        } catch (Exception e2) {
          try {
            date = new SimpleDateFormat(TYPE_HOUR, Locale.CHINA).parse(str);
          } catch (Exception e3) {
            try {
              date = new SimpleDateFormat(TYPE_DATE, Locale.CHINA).parse(str);
            } catch (Exception e4) {
              try {
                date = new SimpleDateFormat(TYPE_MONTH, Locale.CHINA).parse(str);
              } catch (Exception e5) {
                try {
/**/
                  date = new SimpleDateFormat(TYPE_YEAR, Locale.CHINA).parse(str);
                } catch (Exception e6) {
                  e6.printStackTrace();
                }
              }
            }
          }
        }
      }
    }
    return date;
  }

  /**
   * 解析date.
   *
   * @return 要么为空字符串, 要么为正确解析.
   */
  @Deprecated public static String parseTimeToString(Date date, String type) {
    String result = "";
    try {
      result = android.text.format.DateFormat.format(type, date).toString();
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
    return result;
  }

  /**
   * 解析date.
   *
   * @return 要么为空字符串, 要么为正确解析.
   */
  @Deprecated public static Date parseStringToTime(String dateStr, String type) {

    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat(type, Locale.CHINA);
      return dateFormat.parse(dateStr);
    } catch (Exception e) {
      return null;
    }
  }

  @Deprecated public static String dateToString(String date, String type) throws ParseException {
    if (date == null) {
      return null;
    }
    java.util.Date dateNew = sFormat.parse(date);
    return dateToString(dateNew, type);
  }

  /**
   * 日期转化毫秒
   *
   * @param currTime：系统当前时间 使用Context的时候传递ApplicationContext   。
   */
  public static String dateToTimeInMillis(Context context, String date, Date currTime) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String time = format.format(currTime);
    long dateMillis = 0;
    long timeMillis = 0;
    try {
      dateMillis = format.parse(date).getTime();
      timeMillis = format.parse(time).getTime();
    } catch (ParseException e) {
      e.printStackTrace();
    }

    long differenceTime = timeMillis - dateMillis;

    long hour = 60 * 60 * 1000L;
    long day = 24 * 60 * 60 * 1000L;
    long month = 30 * 24 * 60 * 60 * 1000L;
    long year = 12 * 30 * 24 * 60 * 60 * 1000L;

    int months = Calendar.MONTH;
    int years = Calendar.YEAR;

    if ((0 < differenceTime) && (differenceTime < hour)) {
      return differenceTime / (1000 * 60) + context.getString(R.string.topicMinutes);
    } else if (differenceTime < day) {
      return differenceTime / (1000 * 60 * 60) + context.getString(R.string.topicHours);
    } else if (differenceTime < month) {
      return differenceTime / (1000 * 60 * 60 * 24) + context.getString(R.string.topicDays);
    } else if (differenceTime < year) {
      switch (months) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
          return differenceTime / (1000L * 60 * 60 * 24 * 31) + context.getString(
              R.string.topicMonths);
        case 4:
        case 6:
        case 9:
        case 11:
          return differenceTime / (1000L * 60 * 60 * 24 * 30) + context.getString(
              R.string.topicMonths);
        default:
          if ((years % 4 == 0 && years % 400 != 0) || years % 400 == 0) {
            return differenceTime / (1000L * 60 * 60 * 24 * 29) + context.getString(
                R.string.topicMonths);
          } else {
            return differenceTime / (1000L * 60 * 60 * 24 * 28) + context.getString(
                R.string.topicMonths);
          }
      }
    } else {
      return differenceTime / (1000L * 60 * 60 * 24 * 30 * 12) + context.getString(
          R.string.topicYears);
    }
  }

  /**
   * 获取小时和分钟的long值 2015-11-30 09:00获取后为09:00的毫秒值
   *
   * @param time 字符串的时间格式 "2015-11-30 09:00"
   */
  public static long getHourAndMinute(String time) {
    String[] date = time.split(" ", time.length());
    String hourAndMinu = date[1].toString();

    String[] splitTime = hourAndMinu.split(":", hourAndMinu.length());
    long hour = Long.parseLong(splitTime[0].toString()) * (60 * 60 * 1000);
    long minutes = Long.parseLong(splitTime[1].toString()) * (60 * 1000);
    long hourAndMinute = hour + minutes;
    return hourAndMinute;
  }

  /** 获取指定日期的某个时刻 */
  public static Date getHourOfDay(Date date, int hour) {
    if (date == null) date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    return cal.getTime();
  }

  /**
   * 判断开始时间是否超过结束时间 ，时间格式为 2016-1-12类型
   *
   * @param startTime 开始时间
   * @param endTime 结束时间
   */

  public static boolean startBeforeEnd(String startTime, String endTime) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date startDate;
    Date endDate;
    try {
      startDate = format.parse(startTime);
      endDate = format.parse(endTime);

      if (startDate.before(endDate)) {
        return true;
      } else {
        return false;
      }
    } catch (ParseException e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * 获取当月第一天,时间格式2016-1-25
   */

  public static String getFirstDay() {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 获取当年每月的第一天
    Calendar begin = Calendar.getInstance();
    begin.set(Calendar.DAY_OF_MONTH, begin.getActualMinimum(Calendar.DAY_OF_MONTH));
    begin.set(Calendar.SECOND, 0);
    begin.set(Calendar.HOUR_OF_DAY, 0);
    begin.set(Calendar.MINUTE, 0);
    String start = sdf.format(begin.getTime());
    return start;
  }

  /**
   * 获取本周开始时间
   */
  @Deprecated public static Date getFirstDateOfWeek() {
    Calendar calendar = Calendar.getInstance();
    int min = calendar.getActualMinimum(Calendar.DAY_OF_WEEK); //获取周开始基准
    LogUtil.i("min=" + min);//1.
    int current = calendar.get(Calendar.DAY_OF_WEEK); //获取当天周内天数
    LogUtil.i("current=" + current);//2.
    calendar.add(Calendar.DAY_OF_WEEK, min - current + 1); //当天-基准，获取周开始日期,默认是周日,加1改为周一.
    return calendar.getTime();
  }

  public static long getTimestamp() {
    return System.currentTimeMillis() / 1000;
  }

  /**
   * 获取本周结束时间
   */
  @Deprecated public static Date getLastDateOfWeek() {
    Date firstDate = getFirstDateOfWeek();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(firstDate);
    calendar.add(Calendar.DAY_OF_WEEK, 6); //开始+6，获取周结束日期
    return calendar.getTime();
  }

  public static Date getBeginWeekByDate(Date time) {

    Calendar cal = Calendar.getInstance();
    cal.setTime(time);

    int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
    if (1 == dayWeek) { //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
      cal.add(Calendar.DAY_OF_MONTH, -1);
    }
    cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
    int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
    cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);//根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
    cal.setTime(getBeginOfDay(cal.getTime()));
    return cal.getTime();
  }

  public static Date getEndWeekByDate(Date date) {
    Date beginDate = getBeginWeekByDate(date);
    Calendar cal = Calendar.getInstance();
    cal.setTime(beginDate);
    cal.add(Calendar.DATE, 6);
    cal.setTime(getEndofDay(cal.getTime()));
    return cal.getTime();
  }

  /**
   * 获取前几个月第一天,时间格式2016-1-25
   */

  public static String getBeforeMonthFirstDay(int beforeMonth) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 获取当年每月的第一天
    Calendar begin = Calendar.getInstance();
    begin.add(Calendar.MONTH, -beforeMonth); // 一个月
    begin.set(Calendar.DAY_OF_MONTH, begin.getActualMinimum(Calendar.DAY_OF_MONTH));
    begin.set(Calendar.HOUR_OF_DAY, 0);
    begin.set(Calendar.MINUTE, 0);
    begin.set(Calendar.SECOND, 0);
    String start = sdf.format(begin.getTime());

    return start;
  }

  /**
   * 获取当月最后一天，时间格式2016-1-25
   */
  public static String getLastDay() {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 获取当前月最后一天
    Calendar ca = Calendar.getInstance();
    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
    String end = sdf.format(ca.getTime());

    return end;
  }

  /**
   * @return 获取一天的结束时间
   */
  public static Date getEndofDay(Date date) {
    if (date == null) return null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    return calendar.getTime();
  }

  /**
   * @return 获取一天的开始时间
   */
  public static Date getBeginOfDay(Date date) {
    if (date == null) return null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    return calendar.getTime();
  }

  /**
   * 获取前几个月最后一天，时间格式2016-1-25
   */
  public static String getBeforeMonthLastDay(int beforeMonth) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 获取当前月最后一天
    Calendar ca = Calendar.getInstance();
    ca.add(Calendar.MONTH, -beforeMonth); // 一个月
    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
    String end = sdf.format(ca.getTime());

    return end;
  }

  /**
   * 获取当前日期往前推一个月：当前时间2016-2-25，获取时间格式2016-1-25
   */
  @Deprecated public static String getBeforeMonth() {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    // cl.add(Calendar.DAY_OF_YEAR, -1); //一天
    // cl.add(Calendar.WEEK_OF_YEAR, -1); //一周
    calendar.add(Calendar.MONTH, -1); // 一个月
    Date dateFrom = calendar.getTime();
    String beforeMonth = dateToString(dateFrom, TYPE_DATE);
    return beforeMonth;
  }

  /**
   * 获取最近三个月，以当前时间为起点：时间格式2016-1-25
   */
  @Deprecated public static String getBeforeThreeMonth() {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    // cl.add(Calendar.DAY_OF_YEAR, -1); //一天
    // cl.add(Calendar.WEEK_OF_YEAR, -1); //一周
    calendar.add(Calendar.MONTH, -3); // 一个月
    Date dateFrom = calendar.getTime();
    String beforeMonth = dateToString(dateFrom, TYPE_DATE);
    return beforeMonth;
  }

  /**
   * 获取一个月前日期，以当前时间为起点：时间格式为时间戳
   */
  @Deprecated public static Date getBeforeOneMonth() {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    // cl.add(Calendar.DAY_OF_YEAR, -1); //一天
    // cl.add(Calendar.WEEK_OF_YEAR, -1); //一周
    calendar.add(Calendar.MONTH, -1); // 一个月
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 获取几个月前日期，以当前时间为起点：时间格式为时间戳,
   * int number ：传几就是获取几个月
   */
  public static Date getBeforeMonth(int number) {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    calendar.add(Calendar.MONTH, -number); // 一个月
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 获取几个月后日期，以当前时间为起点：时间格式为时间戳,
   * int number ：传几就是获取几个月
   */
  public static Date getAfterMonth(int number) {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    calendar.add(Calendar.MONTH, +number); // 一个月
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 获取几年前日期，以当前时间为起点：时间格式为时间戳,
   * int number ：传几就是获取几个月
   */
  public static Date getBeforeYear(int number) {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    calendar.add(Calendar.YEAR, -number); // 几年前
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 获取几天前日期，以当前时间为起点：时间格式为时间戳,
   * int number ：传几就是获取几个月
   */
  public static Date getBeforeDay(int number) {
    Date dateNow = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    calendar.add(Calendar.DAY_OF_YEAR, -number); // 天前
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 获取后几天，以传的date时间为起点：时间格式为时间戳
   */
  public static Date getAfterDay(Date date, int day) {
    if (date == null) return null;
    Date dateNow = date;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    calendar.add(Calendar.DAY_OF_YEAR, +day); //一天
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 由于服务端无法查询当前日期，所以封装此方法用于在当前日期推迟多少天。
   */
  public static String getAfterDayTotring(String str, int day) {
    Date endDate = MyDateUtil.stringToDate(str, MyDateUtil.TYPE_DATE);
    endDate = MyDateUtil.getAfterDay(endDate, day);
    return MyDateUtil.dateToString(endDate, MyDateUtil.TYPE_DATE);
  }

  /**
   * 由于服务端无法查询当前日期，所以封装此方法用于在当前日期推迟多少天。
   */
  public static String getAfterDayTotring(Date date, int day) {

    date = MyDateUtil.getAfterDay(date, day);
    return MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
  }

  /**
   * 获取前几天，以传的date时间为起点：时间格式为时间戳
   */
  public static Date getBeforDay(Date date, int day) {
    Date dateNow = date;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateNow);
    calendar.add(Calendar.DAY_OF_YEAR, -day); //一天
    Date dateFrom = calendar.getTime();
    return dateFrom;
  }

  /**
   * 获取当月最后一天，时间格式date
   */
  public static Date getLastDayDate() {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 获取当前月最后一天
    Calendar ca = Calendar.getInstance();
    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
    Date dateFrom = ca.getTime();

    return dateFrom;
  }

  /**
   * 是否在时间段之内
   *
   * @param startDate 开始时间
   * @param endDate 结束时间
   * @param date 需要判断的时间
   */
  public static boolean isBetween(Date startDate, Date endDate, Date date) {
    return date.before(endDate) && date.after(startDate);
  }

  /**
   * 生成订单编号 时间时分秒+三位随机数,类似于20170323185952795
   */
  public static String getOrderNo() {
    int i = new java.util.Random().nextInt(900) + 100;
    return parseTimeToString(new Date(), "yyyyMMddHHmmss") + i;
  }

  public static boolean isSameDay(Date date1, Date date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(date1);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(date2);
    int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
    int day2 = calendar2.get(Calendar.DAY_OF_MONTH);
    return day1 == day2;
  }
}
